package com.saer.client.grid.admin.permissions;

import java.util.ArrayList;
import java.util.List;

import com.saer.client.dto.UserInfoDto;
import com.saer.client.grid.AutoFitListGrid;
import com.saer.client.grid.record.admin.permissions.UserInfoRecord;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;

public class UserDetailsGrid extends AutoFitListGrid {
	
	private PermissionsGrid userPermissions;
	private PermissionsGrid allPermissions;
	
	public UserDetailsGrid(PermissionsGrid userPermissionsGrid,
			PermissionsGrid allPermissionsGrid) {

		this.userPermissions = userPermissionsGrid;
		this.allPermissions = allPermissionsGrid;

		this.setSize("100%", "100%");
		this.setEmptyMessage("User Details");

		ListGridField userIdField = new ListGridField("userId", "User Id");
		ListGridField firstNameField = new ListGridField("firstName", "First Name");
		ListGridField lastNameField = new ListGridField("lastName", "Last Name");
		ListGridField userStatusField = new ListGridField("userStatus", "User Status");
		ListGridField userTypeField = new ListGridField("userType", "User Type");

		this.setFields(userIdField, firstNameField, lastNameField,
				userStatusField, userTypeField);

		this.addCellClickHandler(new CellClickHandler() {
			public void onCellClick(CellClickEvent event) {
				clearGrids();
				UserInfoRecord record = (UserInfoRecord) event.getRecord();
				userPermissions.loadPermissions(record.getUserId());
				allPermissions.loadPermissions(record.getUserId());
			}
		});
	}
	
	private void clearGrids() {
		userPermissions.clearData();
		allPermissions.clearData();
	}
    
	public void setData(List<UserInfoDto> userInfoList) {
		ArrayList<UserInfoRecord> userInfoRecordList = new ArrayList<UserInfoRecord>();

		for (UserInfoDto userInfo : userInfoList) {
			userInfoRecordList.add(new UserInfoRecord(
					userInfo.getUserId(),
					String.valueOf(userInfo.getUserStatus()),
					userInfo.getFirstName(),
					userInfo.getLastName(),
					userInfo.getUserType() != null ? String.valueOf(userInfo.getUserType()) : "Undefined"));
		}

		this.setData(userInfoRecordList.toArray(new UserInfoRecord[userInfoRecordList.size()]));
	}

	public PermissionsGrid getUserPermissions() {
		return userPermissions;
	}

	public PermissionsGrid getAllPermissions() {
		return allPermissions;
	}
    
}
